﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class Base : Form
    {
        public SerialPort port;
        private string portName;
        public void connect(string portName)
        {
            if (port != null)
            {
                port.Close();
            }
            this.portName = portName;
            port = new SerialPort(portName, 300, Parity.None, 8, StopBits.One);
            port.DtrEnable = true;//for 32u4
            port.DiscardNull = false;
            port.Open();
            port.WriteTimeout = 100;
        }
        public uint readFromPort()
        {
            int val = port.BytesToRead;
            if (val == 4)
            {
                uint ret = 0;
                port.Read(buff, 0, 4);
                ret |= ((uint)buff[0]) << 24;
                ret |= ((uint)buff[1]) << 16;
                ret |= ((uint)buff[2]) << 8;
                ret |= ((uint)buff[3]);
                return ret;
            }
            else if (val > 4)
            {
                port.Read(buff, 0, val);
                int a = buff[0];
            }
            long time = DateTime.Now.Ticks;
            while (true)
            {
                val = port.BytesToRead;
                if (val == 4)
                {
                    uint ret = 0;
                    port.Read(buff, 0, 4);
                    ret |= ((uint)buff[0]) << 24;
                    ret |= ((uint)buff[1]) << 16;
                    ret |= ((uint)buff[2]) << 8;
                    ret |= ((uint)buff[3]);
                    return ret;
                }
                else if (val > 4)
                {
                    port.Read(buff, 0, val);
                }
                if (DateTime.Now.Ticks - time > 1000000)
                {
                    throw new Exception();
                }
            }
        }

        byte[] buff = new byte[1024];
        public void portWriteNew(byte cmd, byte val)
        {
            buff[0] = cmd;
            buff[1] = val;
            if (port != null)
            {
                while (true)
                {
                    try
                    {
                        port.Write(buff, 0, 2);
                       
                        return;
                    }
                    catch (Exception ex)
                    {
                        port.Dispose();
                        Thread.Sleep(1000);
                        connect(this.portName);
                    }
                }
            }
        }
    }
}
